package com.atguigu.gmall.cart.api;

import com.atguigu.gmall.cart.model.CartInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: atguigu
 * @create: 2023-03-10 10:17
 */
@RestController
@RequestMapping("/api/cart")
public class CartApiController {

    @Autowired
    private CartService cartService;


    /**
     * 查询指定用户购物车中选中商品列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/getCartCheckedList/{userId}")
    public List<CartInfo> getCartCheckedList(@PathVariable("userId") Long userId) {
        return cartService.getCartCheckedList(userId);
    }

    /**
     * 提供给移动端 全选购物车数据
     *
     * @param isChecked
     * @param request
     * @return
     */
    @GetMapping("/allCheckCart/{isChecked}")
    public Result allCheckCart(@PathVariable Integer isChecked, HttpServletRequest request) {
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  判断用户Id 为空
        if (StringUtils.isBlank(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
        //  调用方法
        this.cartService.allCheckCart(userId, isChecked);
        //  默认返回
        return Result.ok();
    }


    /**
     * 清空购物车商品
     * @param request
     * @return
     */
    @GetMapping("clearCart")
    public Result clearCart(HttpServletRequest request){
        // 如何获取userId
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)) {
            // 获取临时用户Id
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.clearCart(userId);
        return Result.ok();
    }
}
